package com.mice.game
{
	import com.mice.event.GameEvent;
	import com.mice.game.core.Actor;
	import com.mice.game.core.Fighter;
	import com.mice.game.core.Player;
	import com.mice.game.trigger.AiTrigger;
	import com.mice.game.trigger.DamageTrigger;
	import com.mice.game.trigger.EnergyTrigger;
	import com.mice.game.trigger.FighterTrigger;
	import com.mice.game.trigger.SpawnTrigger;
	import com.mice.model.AppVO;
	
	import flash.display.Sprite;
	import flash.events.Event;

	public class GameEngine{
		private static var _instance:GameEngine;

		/**
		 * 监听,并派发EnterFrame
		 */		
		public var root:Sprite;

		public var player:Player;
		public var ai:Player;

		public var playerBoss:Fighter;
		public var aiBoss:Fighter;

		public function GameEngine(){}

		public static function get instance():GameEngine{
			if (_instance == null)
				_instance = new GameEngine();
			return _instance;
		}

		public function start(level:int):void{
			root.addEventListener(Event.ENTER_FRAME, onFrame);
			EnergyTrigger.instance.player = player;
			EnergyTrigger.instance.ai = ai;
			AiTrigger.instance.ai = ai;

			playLevel(level);
		}

		public function playLevel(level:int):void{
			playerBoss = SpawnTrigger.instance.spawn(1000 + level, level, player.team);
			aiBoss = SpawnTrigger.instance.spawn(2000 + level, level, ai.team);
			
			if (player.team == Player.TEAM_BLUE){
				FighterTrigger.instance.addBlueFighter(playerBoss);
				FighterTrigger.instance.addRedFighter(aiBoss);
			}else {
				FighterTrigger.instance.addBlueFighter(aiBoss);
				FighterTrigger.instance.addRedFighter(playerBoss);
			}
		}
		
		public function stop():void{
			root.removeEventListener(Event.ENTER_FRAME, onFrame);
			
			AiTrigger.instance.reset();
			EnergyTrigger.instance.reset();
			FighterTrigger.instance.reset();
		}

		private function onFrame(e:Event):void{
			EnergyTrigger.instance.update();

			AiTrigger.instance.update();
			FighterTrigger.instance.update();
			DamageTrigger.instance.update();

			if (aiBoss.isDead){
				player.dispatchEvent(new GameEvent(GameEvent.BATTLE_SUCC));
				stop();
			}else if (playerBoss.isDead){
				player.dispatchEvent(new GameEvent(GameEvent.BATTLE_LOSE));
				stop();
			}
		}
	}
}

